<?php
// api.php - 处理图片编辑请求
// include 'cookie.php';
// 临时启用错误显示（用于调试）
ini_set('display_errors', 1);
error_reporting(E_ALL);

// 增加超时时间
set_time_limit(300); // 5分钟
ini_set('max_execution_time', 300);

header('Content-Type: application/json');
$api_id = isset($_GET['api_id']) ? $_GET['api_id'] : '38502';
$user = isset($_COOKIE['enorg']) ? $_COOKIE['enorg'] : 'bozo';

// 处理缩略图压缩请求
if ($api_id === 'thumbnail_compress') {
    handleThumbnailCompression($user);
    exit;
}

// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '只允许POST请求']);
    exit;
}

// 获取请求数据
$input = json_decode(file_get_contents('php://input'), true);

// 验证必需字段
if (!isset($input['prompt']) || !isset($input['image']) || !isset($input['batch_size']) || !isset($input['resolution'])) {
    echo json_encode(['success' => false, 'message' => '缺少必需参数']);
    exit;
}

$prompt = $input['prompt'];
$imagePath = $input['image'];
$batchSize = (int)$input['batch_size'];
$resolution = $input['resolution'];

// 验证批次数量
if ($batchSize < 1 || $batchSize > 4) {
    echo json_encode(['success' => false, 'message' => '批次数量必须在1-4之间']);
    exit;
}

// 验证图片路径
if (!file_exists($imagePath)) {
    echo json_encode(['success' => false, 'message' => '图片文件不存在']);
    exit;
}

// 获取API密钥（从cookie、环境变量或配置文件中）
$apiKey = '';

// 首先尝试从cookie中获取BIZY_KEY
if (isset($_COOKIE['BIZY_KEY']) && !empty($_COOKIE['BIZY_KEY'])) {
    $apiKey = $_COOKIE['BIZY_KEY'];
}

// 如果cookie中没有，尝试从环境变量中获取
if (!$apiKey) {
    $apiKey = getenv('BIZYAIR_API_KEY');
}

// 如果环境变量中也没有，尝试从文件中读取
if (!$apiKey) {
    $envFile = 'BizyAIR/'.$user.'-BIZYAIR_API_KEY.env';
    if (file_exists($envFile)) {
        $apiKeys = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        // 使用第一个密钥
        $apiKey = trim($apiKeys[0]);
    }
}

if (!$apiKey) {
    echo json_encode(['success' => false, 'message' => '未配置API密钥']);
    exit;
}

// 判断是本地测试还是网络站点
$isLocal = (strpos($imagePath, 'http') === false);

// 准备图片数据
$imageDataValue = "";

if ($isLocal) {
    // 本地测试：将图片转换为base64编码
    $imageData = file_get_contents($imagePath);
    if ($imageData === false) {
        echo json_encode(['success' => false, 'message' => '无法读取图片文件']);
        exit;
    }

    // 获取图片MIME类型
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $imagePath);
    finfo_close($finfo);

    // 转换为base64
    $imageDataValue = 'data:' . $mimeType . ';base64,' . base64_encode($imageData);
} else {
    // 网络站点：直接使用图片URL
    $imageDataValue = $imagePath;
}

// 准备API请求数据
// $apiData = [
//     "web_app_id" => 38502,
//     "suppress_preview_output" => false,
//     "input_values" => [
//         "76:TextEncodeQwenImageEdit.prompt" => $prompt,
//         "78:LoadImage.image" => $imageDataValue,
//         "97:SDXLEmptyLatentSizePicker+.resolution" => $resolution,
//         "97:SDXLEmptyLatentSizePicker+.batch_size" => $batchSize
//     ]
// ];
// 定义API配置数组
$apiConfigs = [
    '38502' => [
        "web_app_id" => 38502,
        "suppress_preview_output" => false,
        "input_values" => [
            "76:TextEncodeQwenImageEdit.prompt" => $prompt,
            "78:LoadImage.image" => $imageDataValue,
            "97:SDXLEmptyLatentSizePicker+.resolution" => $resolution,
            "97:SDXLEmptyLatentSizePicker+.batch_size" => $batchSize
        ]
    ],
    '38783' => [
        "web_app_id" => 38783,
        "suppress_preview_output" => true,
        "input_values" => [
            "11:TextEncodeQwenImageEditPlus.prompt" => $prompt,
            "31:LoadImage.image" => $imageDataValue,
            "14:KSampler.steps" => 4
        ]
    ],
    '38694' => [
        "web_app_id" => 38694,
        "suppress_preview_output" => true,
        "input_values" => [
            "78:LoadImage.image" => $imageDataValue
        ]
    ],
    '38913' => [
        "web_app_id" => 38913,
        "suppress_preview_output" => true,
        "input_values" => [
            "31:LoadImage.image" => $imageDataValue,
            "11:TextEncodeQwenImageEditPlus.prompt" => $prompt
        ]
    ],
    '38914' => [
        "web_app_id" => 38914,
        "suppress_preview_output" => true,
        "input_values" => [
            "31:LoadImage.image" => $imageDataValue,
            "11:TextEncodeQwenImageEditPlus.prompt" => $prompt
        ]
    ],
    '38915' => [
        "web_app_id" => 38915,
        "suppress_preview_output" => true,
        "input_values" => [
            "31:LoadImage.image" => $imageDataValue,
            "11:TextEncodeQwenImageEditPlus.prompt" => $prompt
        ]
    ],
    '38916' => [
        "web_app_id" => 38916,
        "suppress_preview_output" => true,
        "input_values" => [
            "31:LoadImage.image" => $imageDataValue,
            "11:TextEncodeQwenImageEditPlus.prompt" => $prompt
        ]
    ]
    // 可以继续添加其他api_id配置
];

// 获取对应的api数据，如果api_id不存在则使用默认配置
$apiData = isset($apiConfigs[$api_id]) ? $apiConfigs[$api_id] : $apiConfigs['38502'];


// 调用BizyAIR API
$apiUrl = "https://api.bizyair.cn/w/v1/webapp/task/openapi/create";
$ch = curl_init($apiUrl);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($apiData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 5分钟超时

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

// 返回API调用的详细信息用于调试
if ($response === false) {
    echo json_encode([
        'success' => false, 
        'message' => 'API请求失败: ' . $curlError,
        'api_data' => $apiData,
        'api_url' => $apiUrl
    ]);
    exit;
}

// 解析API响应
$result = json_decode($response, true);

if ($httpCode !== 200 || !isset($result['status']) || $result['status'] !== 'Success') {
    echo json_encode([
        'success' => false, 
        'message' => 'API调用失败', 
        'api_response' => $result,
        'http_code' => $httpCode,
        'api_data' => $apiData
    ]);
    exit;
}

// 下载生成的图片并保存
$downloadedImages = [];
if (isset($result['outputs']) && is_array($result['outputs'])) {
    $downloadDir = dirname($imagePath);
    $originalName = pathinfo($imagePath, PATHINFO_FILENAME);
    $timestamp = date('YmdHis');
    
    foreach ($result['outputs'] as $index => $output) {
        if (isset($output['object_url'])) {
            // 下载图片
            $imageData = file_get_contents($output['object_url']);
            if ($imageData !== false) {
                // 生成新文件名（参考API返回数据格式：原图名_时间戳_序号）
                $newFileName = $originalName . '_' . $timestamp . '_' . sprintf('%02d', $index + 1) . '.png';
                $newFilePath = $downloadDir . '/' . $newFileName;
                
                // 保存图片
                if (file_put_contents($newFilePath, $imageData)) {
                    // 成功保存
                    $downloadedImages[] = [
                        'filename' => $newFileName,
                        'path' => $newFilePath,
                        'url' => $output['object_url'],
                        'index' => $index + 1,
                        'timestamp' => $timestamp
                    ];
                } else {
                    echo json_encode([
                        'success' => false, 
                        'message' => '保存图片失败: ' . $newFileName,
                        'api_response' => $result
                    ]);
                    exit;
                }
            } else {
                echo json_encode([
                    'success' => false, 
                    'message' => '下载图片失败: ' . $output['object_url'],
                    'api_response' => $result
                ]);
                exit;
            }
        }
    }
    
    echo json_encode([
        'success' => true, 
        'message' => '图片编辑成功，生成了' . count($result['outputs']) . '张图片',
        'api_response' => $result,
        'downloaded_images' => $downloadedImages,
        'total_generated' => count($result['outputs']),
        'original_image' => $imagePath
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'API响应中没有图片数据',
        'api_response' => $result,
        'api_data' => $apiData
    ]);
}

// 处理缩略图压缩功能
function handleThumbnailCompression($user) {
    // 暂时保留$user参数以保持接口一致性，当前版本未使用
    // 检查请求方法
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => '只允许POST请求']);
        exit;
    }

    // 获取请求数据
    $input = json_decode(file_get_contents('php://input'), true);

    // 验证必需参数
    if (!isset($input['tempPath']) || !isset($input['exludedFolders'])) {
        echo json_encode(['success' => false, 'message' => '缺少必需参数']);
        exit;
    }

    $tempPath = $input['tempPath'];
    $excludedFolders = $input['exludedFolders'];
    $compressedCount = 0;
    $failedCount = 0;

    // 可选：清理嵌套的缩略图
    function cleanNestedThumbnails($directory) {
        if (!is_dir($directory)) {
            return;
        }

        $items = scandir($directory);
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') {
                continue;
            }

            $fullPath = $directory . '/' . $item;

            if (is_file($fullPath)) {
                // 删除包含多个 _thumb 的嵌套缩略图
                if (substr_count($item, '_thumb') > 1) {
                    unlink($fullPath);
                    error_log("已删除嵌套缩略图: " . $fullPath);
                }
            }
        }
    }

    // 清理现有的嵌套缩略图
    cleanNestedThumbnails($tempPath);
    foreach ($excludedFolders as $folder) {
        $folderPath = $tempPath . '/' . $folder;
        if (is_dir($folderPath)) {
            cleanNestedThumbnails($folderPath);
        }
    }

    $tempPath = $input['tempPath'];
    $excludedFolders = $input['exludedFolders'];
    $compressedCount = 0;
    $failedCount = 0;

    // 支持的图片格式
    $imageExtensions = ['jpg', 'jpeg', 'png', 'webp'];

    // 递归扫描目录中的图片文件
    function findImages($directory, $excludedFolders, $imageExtensions) {
        $images = [];

        if (!is_dir($directory)) {
            return $images;
        }

        $items = scandir($directory);
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') {
                continue;
            }

            $fullPath = $directory . '/' . $item;

            if (is_dir($fullPath)) {
                // 跳过排除的文件夹
                if (!in_array($item, $excludedFolders)) {
                    $images = array_merge($images, findImages($fullPath, $excludedFolders, $imageExtensions));
                }
            } else {
                // 检查是否是图片文件
                $extension = strtolower(pathinfo($item, PATHINFO_EXTENSION));
                if (in_array($extension, $imageExtensions)) {
                    // 跳过所有已经是缩略图的文件（包含_thumb的）
                    if (strpos($item, '_thumb') !== false) {
                        continue;
                    }
                    $images[] = $fullPath;
                }
            }
        }

        return $images;
    }

    // 获取所有图片文件
    $allImages = findImages($tempPath, $excludedFolders, $imageExtensions);

    foreach ($allImages as $imagePath) {
        // 跳过已经是webp的文件（这些可能是之前压缩的）
        $extension = strtolower(pathinfo($imagePath, PATHINFO_EXTENSION));
        if ($extension === 'webp') {
            continue;
        }

        // 检查所有可能的缩略图变体是否已存在
        $fileName = pathinfo($imagePath, PATHINFO_FILENAME);
        $extension = pathinfo($imagePath, PATHINFO_EXTENSION);
        $directory = pathinfo($imagePath, PATHINFO_DIRNAME);

        // 检查所有可能的缩略图变体
        $possibleThumbnails = [
            $fileName . '_thumb.' . $extension,
            $fileName . '_thumb_thumb.' . $extension,
            $fileName . '_thumb_thumb_thumb.' . $extension,
            // 可以继续添加更多可能的变体
        ];

        $thumbnailExists = false;
        foreach ($possibleThumbnails as $thumbName) {
            if (file_exists($directory . '/' . $thumbName)) {
                $thumbnailExists = true;
                break;
            }
        }

        if ($thumbnailExists) {
            continue;
        }

        try {
            error_log('开始处理图片: ' . $imagePath);

            // 使用GD库创建缩略图
            $sourceImage = null;

            try {
                // 根据不同格式创建图像资源
                switch ($extension) {
                    case 'jpg':
                    case 'jpeg':
                        $sourceImage = imagecreatefromjpeg($imagePath);
                        break;
                    case 'png':
                        $sourceImage = imagecreatefrompng($imagePath);
                        break;
                    default:
                        $sourceImage = imagecreatefromstring(file_get_contents($imagePath));
                }

                if (!$sourceImage) {
                    throw new Exception('无法创建图像资源: ' . $imagePath);
                }

                // 获取原图尺寸
                $originalWidth = imagesx($sourceImage);
                $originalHeight = imagesy($sourceImage);

                error_log('原图尺寸: ' . $originalWidth . 'x' . $originalHeight);

                // 计算缩略图尺寸，保持宽高比
                $targetWidth = 400;
                $targetHeight = 400;

                // 计算缩放比例
                $ratio = min($targetWidth / $originalWidth, $targetHeight / $originalHeight);
                $newWidth = (int)($originalWidth * $ratio);
                $newHeight = (int)($originalHeight * $ratio);

                error_log('缩略图尺寸: ' . $newWidth . 'x' . $newHeight);

                // 创建缩略图
                $thumbnail = imagecreatetruecolor($newWidth, $newHeight);
                if (!$thumbnail) {
                    throw new Exception('无法创建缩略图画布');
                }

                // 设置白色背景
                $bgColor = imagecolorallocate($thumbnail, 255, 255, 255);
                imagefilledrectangle($thumbnail, 0, 0, $newWidth, $newHeight, $bgColor);

                // 重新采样以获得更好的质量
                if (!imagecopyresampled($thumbnail, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight)) {
                    throw new Exception('图像重采样失败');
                }

            } finally {
                // 确保源图像资源被释放
                if ($sourceImage) {
                    imagedestroy($sourceImage);
                }
            }

            // 统一保存为jpg格式的缩略图
            $outputPath = pathinfo($imagePath, PATHINFO_DIRNAME) . '/' . pathinfo($imagePath, PATHINFO_FILENAME) . '_thumb.jpg';

            error_log('输出路径: ' . $outputPath);

            // 检查输出目录是否可写
            $outputDir = pathinfo($outputPath, PATHINFO_DIRNAME);
            if (!is_writable($outputDir)) {
                throw new Exception('输出目录不可写: ' . $outputDir);
            }

            // 首先清除可能的输出文件（避免残留数据）
            if (file_exists($outputPath)) {
                unlink($outputPath);
            }

            // 验证缩略图数据是否有效
            ob_start(); // 开始输出缓冲
            imagejpeg($thumbnail, null, 85); // 输出到buffer
            $imageData = ob_get_clean(); // 获取数据
            ob_end_clean(); // 清理缓冲

            if (empty($imageData)) {
                throw new Exception('缩略图为空数据');
            }

            // 直接写入文件
            $handle = fopen($outputPath, 'wb');
            if (!$handle) {
                throw new Exception('无法打开文件进行写入: ' . $outputPath);
            }

            $bytesWritten = fwrite($handle, $imageData);
            fclose($handle);

            if ($bytesWritten === false) {
                throw new Exception('写入文件失败: ' . $outputPath);
            }

            // 检查文件是否成功创建
            if (!file_exists($outputPath)) {
                throw new Exception('缩略图文件未创建');
            }

            // 检查文件大小
            $fileSize = filesize($outputPath);
            if ($fileSize === 0) {
                throw new Exception('缩略图文件大小为0');
            }

            error_log('缩略图创建成功: ' . $outputPath . ' (大小: ' . $fileSize . ' bytes)');

            // 验证生成的图片
            $verifyImage = imagecreatefromjpeg($outputPath);
            if (!$verifyImage) {
                throw new Exception('生成的缩略图无效');
            }
            imagedestroy($verifyImage);

            // 释放内存
            imagedestroy($thumbnail);

            $compressedCount++;

        } catch (Exception $e) {
            error_log('压缩失败: ' . $imagePath . ' - ' . $e->getMessage());
            $failedCount++;
        }
    }

    echo json_encode([
        'success' => true,
        'message' => '缩略图压缩完成',
        'compressed_count' => $compressedCount,
        'failed_count' => $failedCount,
        'total_images' => count($allImages)
    ]);
}
